package com.hp.bon.sgw.wh.channel.invoices;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hp.bon.sgw.wh.channel.common.BizConsts;
import com.hp.bon.sgw.wh.channel.invoices.bizSlot.HttpClientUtils;
import org.simpleframework.http.Query;
import org.simpleframework.http.Request;

import com.hp.bon.sgw.wh.channel.common.BizParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

public class RequestParser {

    private static final Logger _log = LoggerFactory.getLogger(RequestParser.class);

    public BizParam doParser(Request request) {
        BizParam param = new BizParam();
        String requestBody = HttpClientUtils.getRequestBody(request);
        String requestPath = request.getPath().getPath();
        String requestMethod = request.getMethod();
        param.setParam(BizConsts.KEY_REQUEST_BODY, requestBody);
        param.setParam(BizConsts.KEY_REQUEST_PATH, requestPath);
        param.setParam(BizConsts.KEY_REQUEST_METHOD, requestMethod);
        String contentType = "";
        String appId = "";
        String appKey = "";
        String requestId = "";
        String regionId = "";
        try {
            contentType = request.getValue(BizConsts.RQUEST_HEADER_CONTENT_TYPE);
            appId = request.getValue(BizConsts.RQUEST_HEADER_X_APP_KEY);
            appKey = request.getValue(BizConsts.RQUEST_HEADER_X_APP_KEY);
            requestId = request.getValue(BizConsts.RQUEST_HEADER_X_CTG_REQUEST_ID);
            regionId = request.getValue(BizConsts.RQUEST_HEADER_X_CTG_REGION_ID);
        } catch (Exception e) {
            _log.error("Failed to get the request header", e);
        }

        param.setParam(BizConsts.RQUEST_HEADER_CONTENT_TYPE, contentType);
        param.setParam(BizConsts.RQUEST_HEADER_X_APP_KEY, appId);
        param.setParam(BizConsts.RQUEST_HEADER_X_APP_KEY, appKey);
        param.setParam(BizConsts.RQUEST_HEADER_X_CTG_REQUEST_ID, requestId);
        param.setParam(BizConsts.RQUEST_HEADER_X_CTG_REGION_ID, regionId);
        // 8个电子发票相关接口，只有一个接为修改发票信息接口：invoiceInformation-patch
        // BizConsts.FLAG_INVOICE_MODIFY先默认给个值
        param.setParam(BizConsts.FLAG_INVOICE_MODIFY, "0");

       /* if (requestPath.endsWith(TMallChannel.INVOICE)) {
            return this.queryInvoice(param, request);
        } else if (requestPath.endsWith(TMallChannel.INVOICEINFORMATION)) {
            return this.queryInvoiceInformation(param, request);
        }*/
        if (requestMethod.endsWith(BizConsts.RQUEST_METHOD_GET)) {
            return this.queryGet(param, request);
        } else if (requestMethod.endsWith(BizConsts.RQUEST_METHOD_POST)) {
            return this.queryPost(param, request);
        }
        return this.queryInvoiceInformation(param, request);
    }

    public BizParam queryGet(BizParam bizParam, Request request) {
        try {


            String invoiceId = getReqValue(request, BizConsts.KEY_INVOICE_INVOICEID);
            String serialNumber = getReqValue(request, BizConsts.RQUEST_KEY_SERIALNUMBER);
            String issueId = getReqValue(request, BizConsts.RQUEST_KEY_ISSUERID);
            String lanId = getReqValue(request, BizConsts.KEY_INVOICE_LANID);
            String type = getReqValue(request, BizConsts.RQUEST_KEY_TYPE);
            //String serialNumber = getReqValue(request, BizConsts.RQUEST_KEY_SERIALNUMBER);
            bizParam.setParam(BizConsts.RQUEST_KEY_SERIALNUMBER, serialNumber);
            bizParam.setParam(BizConsts.KEY_INVOICE_INVOICEID, invoiceId);
            bizParam.setParam(BizConsts.KEY_INVOICE_LANID, lanId);
            bizParam.setParam(BizConsts.RQUEST_KEY_ISSUERID, issueId);
            bizParam.setParam(BizConsts.RQUEST_KEY_TYPE, type);
            //bizParam.setParam(BizConsts.RQUEST_KEY_OBJECTS, objects);
			/*String invoiceId = request.getParameter(BizConsts.KEY_INVOICE_INVOICEID).isEmpty() ?
                    query.get(BizConsts.KEY_INVOICE_INVOICEID) : request.getParameter(BizConsts.KEY_INVOICE_INVOICEID);
            String serialNumber = request.getValue(BizConsts.RQUEST_KEY_SERIALNUMBER).isEmpty() ?
                    query.get(BizConsts.RQUEST_KEY_SERIALNUMBER) : request.getParameter(BizConsts.RQUEST_KEY_SERIALNUMBER);
            String issueId = request.getParameter(BizConsts.RQUEST_KEY_ISSUERID);
            String objects = request.getParameter(BizConsts.RQUEST_KEY_OBJECTS);
            invoiceId = (invoiceId == null ? "" : invoiceId);
            String lanId = request.getValue(BizConsts.KEY_INVOICE_LANID);

            lanId = request.getForm().get(BizConsts.KEY_INVOICE_LANID);
            System.out.println(lanId);

            serialNumber = request.getForm().get(BizConsts.RQUEST_KEY_SERIALNUMBER);
            System.out.println(serialNumber);

            //lanId = ( lanId == null ? "" : lanId );
            String attribute = (String) request.getAttribute(BizConsts.KEY_INVOICE_LANID);
            System.out.println(attribute);
           */
        } catch (Exception e) {
            _log.error("Failed to parse the GET request===>{}", e);
        }
        return bizParam;
    }

    public BizParam queryPost(BizParam bizParam, Request request) {
        try {
            String bodyStr = bizParam.getParamString(BizConsts.KEY_REQUEST_BODY);
            Map<String, Object> stringObjectMap = HttpClientUtils.parseJSON2Map(bodyStr);
            if (stringObjectMap == null || stringObjectMap.isEmpty()) {
                return bizParam;
            }
            for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
                bizParam.setParam(entry.getKey(), entry.getValue());
            }


        } catch (Exception e) {
            _log.info(e.toString());
        }
        return bizParam;
    }


    public BizParam queryInvoiceInformation(BizParam bizParam, Request request) {
        try {

            String requestMethod = request.getMethod();

            if (requestMethod.equals("GET")) {
                // Get
                String lanId = request.getParameter(BizConsts.KEY_INVOICE_LANID) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICE_LANID);
                String type = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_GET_TYPE) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_GET_TYPE);
                String serialNumber = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_GET_SERIALNUMBER) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_GET_SERIALNUMBER);

                bizParam.setParam(BizConsts.KEY_INVOICE_LANID, lanId);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_GET_TYPE, type);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_GET_SERIALNUMBER, serialNumber);
            } else if (requestMethod.equals("POST")) {
                // Post
                String id = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_ID) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_ID);
                String custId = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_CUSTID) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_CUSTID);
                String mobile = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_MOBILE) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_MOBILE);
                String eMail = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_EMAIL) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_EMAIL);
                String automaticPush = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_AUTOMATICPUSH) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_AUTOMATICPUSH);
                String postlanId = request.getParameter(BizConsts.KEY_INVOICE_LANID) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICE_LANID);
                String invoiceHeader = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_INVOICEHEADER) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_INVOICEHEADER);
                String buyerTaxPayerId = request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_BUYERTAXPAYERID) == null ? ""
                        : request.getParameter(BizConsts.KEY_INVOICEINFORMATION_POST_BUYERTAXPAYERID);

                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_ID, id);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_CUSTID, custId);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_MOBILE, mobile);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_EMAIL, eMail);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_AUTOMATICPUSH, automaticPush);
                bizParam.setParam(BizConsts.KEY_INVOICE_LANID, postlanId);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_INVOICEHEADER, invoiceHeader);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_POST_BUYERTAXPAYERID, buyerTaxPayerId);
            } else if (requestMethod.equals("PATCH")) {
                // PATCH
                String bodyContent = request.getContent();
                String requestPath = request.getPath().getPath();
                int one = requestPath.lastIndexOf("/");
                String id = requestPath.substring((one + 1), requestPath.length());
                JSONArray jsonArray = JSON.parseArray(bodyContent);

                JSONArray patchJson = new JSONArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                    com.alibaba.fastjson.JSONObject s1 = jsonArray.getJSONObject(i);
                    com.alibaba.fastjson.JSONObject jsonItem = new JSONObject();
                    jsonItem.put(BizConsts.KEY_INVOICEINFORMATION_PATCH_OP, s1.get("op"));
                    jsonItem.put(BizConsts.KEY_INVOICEINFORMATION_PATCH_PATH, s1.get("path"));
                    jsonItem.put(BizConsts.KEY_INVOICEINFORMATION_PATCH_VALUE, s1.get("value"));
                    patchJson.add(jsonItem);
                }

                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_PATCH_ID, id);
                bizParam.setParam(BizConsts.KEY_INVOICEINFORMATION_PATCH_JSON, patchJson.toJSONString());

                //标记为：修改发票信息接口invoiceInformation-patch
                bizParam.setParam(BizConsts.FLAG_INVOICE_MODIFY, "1");
            }

        } catch (IOException e) {
            _log.info(e.toString());
        }
        return bizParam;
    }


    public String getReqValue(Request req, String key) {
        String value = "";
        try {
            Query query = req.getQuery();
            value = req.getParameter(key);
            _log.info(" field: {}===>[{}]", key, value);
            if (value == null || value.isEmpty()) {
                value = query.get(key);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
        return value;
    }


}
